﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 简单回收组件，需要配合EasyPool 使用
/// </summary>
[AddComponentMenu("Behavior/EasyRecycle")]
public class BhvEasyRecycle : MonoBehaviour
{
    [HideInInspector]
    public float lifeTime = 1.0f;

    [SerializeField]
    private float lifeTimeMax = 1.0f;

    public void ResetLifeTime(float timer = -1)
    {
        if (timer != -1)
        {
            lifeTimeMax = timer;
        }
        lifeTime = lifeTimeMax;
    }


    // Start is called before the first frame update
    void Start()
    {
        this.ResetLifeTime();
    }

    // Update is called once per frame
    void Update()
    {
        //如果lifeTimeMax==0 则不会经过时间流逝，需要通过动画事件调用 CheckRecycle();
        if (lifeTimeMax == 0) return;
        if (lifeTime >= 0)
        {
            lifeTime -= Time.deltaTime;
        }
        else
        {
            CheckRecovery();
        }
    }

    private void CheckRecovery()
    {
        //恢复生命周期最大值
        lifeTime = lifeTimeMax;
        var parentPool = this.GetComponentInParent<BhvEasyPool>();
        if (parentPool)
        {
            parentPool.Put(this.gameObject);
        }
        else
        {
            Destroy(gameObject);
        }
    }

}
